import tempfile
import win32api
import win32print
import os, sys
from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('simhei', 'simhei.ttf'))  # 中文

class pdf_():
    def __init__(self, read_path, text="PDF读取测试", is_print=False, x=100, y=100, save_path='out_pdf.pdf'):
        self.packet = io.BytesIO()
        self.can = canvas.Canvas(self.packet, pagesize=letter)
        self.x = x
        self.y = y
        self.text = text
        self.read_path = read_path
        self.save_path = save_path
        self.is_print_ = is_print
        self.set_font()
        if is_print:
            self.is_print()
        else:
            print("不打印!")

    def set_font(self):
        # 使用Reportlab创建一个新的PDF
        self.can.setLineWidth(.3)
        self.can.setFont('simhei', 12)   # 字体大小
        self.can.drawString(self.x, self.y, self.text, mode=None, charSpace=0, direction=None, wordSpace=None)
        self.can.save()
        self.read_pdf()

    #buffer从偏移0开始
    def read_pdf(self):
        self.packet.seek(0)
        new_pdf = PdfFileReader(self.packet)
        #读取已有的PDF
        existing_pdf = PdfFileReader(open(self.read_path, "rb"))
        output = PdfFileWriter()

        page = existing_pdf.getPage(0)
        page.mergePage(new_pdf.getPage(0))
        output.addPage(page)
        self.save_pdf(output)

    def save_pdf(self, output):
        # 最后，向目标的pdf写出 导出pdf
        outputStream = open(self.save_path, "wb")
        output.write(outputStream)
        outputStream.close()

    def is_print(self):
        # filename = tempfile.mktemp(self.save_path)
        # open(self.save_path, "w").write("This is a test")
        win32api.ShellExecute(
            0,
            "printto",
            self.save_path,
            '"%s"' % win32print.GetDefaultPrinter(),
            ".",
            0
        )

    def out_print2(self):
        printer_name = win32print.GetDefaultPrinter()
        #
        # raw_data could equally be raw PCL/PS read from
        #  some print-to-file operation
        #
        if sys.version_info >= (3,):
            raw_data = bytes("This is a test", "utf-8")
        else:
            raw_data = "This is a test"

        hPrinter = win32print.OpenPrinter(printer_name)
        try:
            hJob = win32print.StartDocPrinter(hPrinter, 1, ("test of raw data", None, "RAW"))
            try:
                win32print.StartPagePrinter(hPrinter)
                win32print.WritePrinter(hPrinter, raw_data)
                win32print.EndPagePrinter(hPrinter)
            finally:
                win32print.EndDocPrinter(hPrinter)
        finally:
            win32print.ClosePrinter(hPrinter)


if __name__=='__main__':
    pdf_('img/OCR1.pdf', "rtghyujkls集合广东佛山", save_path="1234.pdf")